﻿using System.Linq.Dynamic.Core;
using System.Linq.Expressions;

namespace Infrastructure.Repositories;

/// <summary>
/// 菜单仓储
/// </summary>
public class MenuRepository : IMenuRepository
{
    private readonly IApplicationDbContext _dbContext;

    public MenuRepository(IApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    /// <summary>
    /// 获取所有菜单
    /// </summary>
    /// <param name="condition"></param>
    /// <returns></returns>
    public IQueryable<Menu> GetAll(Expression<Func<Menu, bool>>? condition = null)
    {
        IQueryable<Menu> query = _dbContext.Menus
            .OrderByDescending(o => o.Meta.Rank)
            .Include(m => m.Meta)
            .Include(rm => rm.RoleMenus)
                .ThenInclude(r => r.Role)
                    .ThenInclude(ru => ru.UserRoles)
             .AsNoTracking()
             .AsQueryable();

        if (condition != null)
        {
            query = query.Where(condition);
        }

        return query;
    }


    /// <summary>
    /// 通过用户唯一标识获取菜单
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="isSystemAccount"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task<List<Menu>> GetUserMenusByUserIdAsync(long userId, bool isSystemAccount = false, CancellationToken cancellationToken = default)
    {
        var userMenusQuery = GetAll();

        if (!isSystemAccount)
        {
            //userMenusQuery = userMenusQuery
            //    .Where(menu => menu.RoleMenus.Any(rm => rm.Role.UserRoles.Any(ur => ur.UserId == userId)));

            userMenusQuery = userMenusQuery
                .Where(menu => menu.RoleMenus.Any(rm => rm.Role.UserRoles.Any(ur => ur.UserId == userId) && rm.Role.IsActive));
        }

        var userMenus = await userMenusQuery.ToListAsync();
        return userMenus;
    }
}
